//
//  DECXContractInStoreViewController.m
//  DECXInStore
//
//  Created by 程强 on 2017/7/20.
//  Copyright © 2017年 程强. All rights reserved.
//

#import "DECXContractInStoreViewController.h"
#import "DECXManager.h"
#import "DECXContractObj.h"
#import "DECXStoreObj.h"
#import "DECXUploadPictureViewController.h"
#import "DECXPictureFile.h"
#import "KSPickerView.h"

@interface DECXContractInStoreViewController ()<UITextFieldDelegate,KSPickerViewDelegate>
@property (strong, nonatomic) DECXManager *manager;
@property (strong, nonatomic) DECXContractObj *contractInfo;
@property (weak, nonatomic) IBOutlet UITextField *contractTxf;
@property (weak, nonatomic) IBOutlet UILabel *contractNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *contractTypeLbl;
@property (weak, nonatomic) IBOutlet UITextField *billNoTxf;
@property (weak, nonatomic) IBOutlet UITextField *markTxf;
@property (weak, nonatomic) IBOutlet UILabel *seatNoLbl;
@property (weak, nonatomic) IBOutlet UILabel *ownerNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *ownerPhoneLbl;
@property (weak, nonatomic) IBOutlet UILabel *ownerTelLbl;
@property (weak, nonatomic) IBOutlet UILabel *ownerEmailLbl;
@property (weak, nonatomic) IBOutlet UITextField *placeTxf;
@property (weak, nonatomic) IBOutlet UILabel *numLbl;
@property (weak, nonatomic) IBOutlet UILabel *categoryLbl;
@property (weak, nonatomic) IBOutlet UITextField *qualityTxf;
@property (weak, nonatomic) IBOutlet UIButton *storeChoseBtn;
@property (weak, nonatomic) IBOutlet UITextField *stackTxf;
@property (weak, nonatomic) IBOutlet UILabel *storeNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *storeManagerNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *storeManagerPhoneLbl;
@property (weak, nonatomic) IBOutlet UILabel *storeManagerTelLbl;
@property (weak, nonatomic) IBOutlet UILabel *storeManagerEmailLbl;
@property (weak, nonatomic) IBOutlet UILabel *storeAddressLbl;
@property (weak, nonatomic) IBOutlet UILabel *productLogoMarkLbl;
@property (weak, nonatomic) IBOutlet UILabel *productOwnerPicMarkLbl;
@property (weak, nonatomic) IBOutlet UITextField *productPriceTxf;
@property (strong, nonatomic) KSPickerView *storePicker;
@property (strong, nonatomic) NSArray *storeAry;
@property (strong, nonatomic)DECXStoreObj *currentStore;

#pragma mark --- 上传的文件
@property (strong, nonatomic) DECXPictureFile *productLogoFile;
@property (strong, nonatomic) DECXPictureFile *productOwnerFile;
@end

@implementation DECXContractInStoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DECXManager new];
    
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(commitOrder)];
    self.navigationItem.rightBarButtonItem = rightBar;
}
- (void)commitOrder
{
    [self resignFirstResponder];
    if (!_contractInfo) {
        ToastShowInWindow(@"无效的合约信息");
        return;
    }
    if (!_currentStore) {
        ToastShowInWindow(@"无效的仓库信息");
        return;
    }
    if (self.billNoTxf.text.length == 0) {
        ToastShowInWindow(@"请输入提单号");
        return;
    }
    if (self.markTxf.text.length == 0) {
        ToastShowInWindow(@"请输入唛头");
        return;
    }
    if (!self.productLogoFile) {
        ToastShowInWindow(@"请上传货物图片");
        return;
    }
    if (!self.productOwnerFile) {
        ToastShowInWindow(@"请上传货权图片");
        return;
    }
    if ([self.contractInfo.num doubleValue] == 0) {
        ToastShowInWindow(@"合约数量为0吨");
        return;
    }
    if (self.placeTxf.text.length == 0) {
        ToastShowInWindow(@"请输入货物产地");
        return;
    }
    if (self.qualityTxf.text.length == 0) {
        ToastShowInWindow(@"请输入货物质量");
        return;
    }
    if (self.stackTxf.text.length == 0) {
        ToastShowInWindow(@"请输入垛位号");
        return;
    }
    
    DECXContractOrderCommitModel *model = [[DECXContractOrderCommitModel alloc] init];
    model.getlist_id = self.billNoTxf.text;
    model.mark = self.markTxf.text;
    model.img = self.productLogoFile.img;
    model.img_small = self.productLogoFile.img_small;
    
    model.goods_owner = self.contractInfo.user.user_id;
    model.goods_owner_mobile = self.contractInfo.user.user_phone;
    model.goods_owner_phone = self.contractInfo.user.user_tel;
    model.goods_owner_email = self.contractInfo.user.user_email;
    model.goods_owner_prove = self.productOwnerFile.img;
    model.goods_owner_prove_small = self.productOwnerFile.img_small;
    model.inner_weight = self.contractInfo.num;
    model.goods_place = self.placeTxf.text;
    model.goods_type = self.contractInfo.category_id;
    model.depot_quality = self.qualityTxf.text;
    model.stack = self.stackTxf.text;
    
    //仓库人员
    model.depot_responsible = self.currentStore.depotManager.name;
    model.depot_responsible_id = self.currentStore.depotManager.userid;
    model.responsible_mobile = self.currentStore.depotManager.mobile;
    model.responsible_phone = self.currentStore.depotManager.phone;
    model.responsible_email = self.currentStore.depotManager.email;
    model.depot_addr = self.currentStore.depot_addr;
    model.depot_id = self.currentStore.xid;
    
    model.brand_id = self.contractInfo.xid;
    model.brand_price = self.productPriceTxf.text;
    
    [self showHUD];
    weak_Self(self);
    MyUser;
    [[self.manager commitContractStore:user.userid contractOrder:model]subscribeNext:^(id x) {
        ToastShowInWindow(@"合约入仓成功");
        [weakSelf gotoBack];
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        ToastShowInWindow(msg);
    } completed:^{
        [weakSelf hideHUD];
    }];

}
- (IBAction)fetchContractInfoClick:(id)sender
{
    [self resignKeyBoard];
    weak_Self(self);
    [self performBlock:^{
        [weakSelf getContract];
    } delay:0.5];
}
- (void)getContract
{
    if (self.contractTxf.text.length == 0) {
        ToastShowInWindow(@"请填写合约号！");
        return;
    }
    weak_Self(self);
    [self showHUD];
    [[self.manager getContractInfo:self.contractTxf.text]subscribeNext:^(id x) {
        weakSelf.contractInfo = x;
        [weakSelf loadContractInfo];
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        ToastShowInWindow(msg);
    } completed:^{
        [weakSelf hideHUD];
    }];
}
- (void)loadContractInfo
{
    MyUser;
    //席位号登录要验证合约信息
    if (self.inStoreType == kInStoreTypeSeat) {
        if (![self.contractInfo.user.user_id isEqualToString:user.userid]) {
            ToastShowInWindow(@"无效的合约信息");
            self.contractNameLbl.text = @"";
            self.seatNoLbl.text = @"";
            self.ownerNameLbl.text = @"";
            self.ownerPhoneLbl.text = @"";
            self.ownerTelLbl.text = @"";
            self.ownerEmailLbl.text = @"";
            self.numLbl.text = @"";
            self.contractInfo = nil;
            return;
        }
    }

    self.contractNameLbl.text = self.contractInfo.title;
    self.seatNoLbl.text = self.contractInfo.user.user_seat;
    self.ownerNameLbl.text = self.contractInfo.user.user_tname;
    self.ownerPhoneLbl.text = self.contractInfo.user.user_phone.length == 0?@"无":self.contractInfo.user.user_phone;
    self.ownerTelLbl.text = self.contractInfo.user.user_tel.length==0?@"无":self.contractInfo.user.user_tel;
    self.ownerEmailLbl.text = self.contractInfo.user.user_email.length == 0?@"无":self.contractInfo.user.user_email;
    self.numLbl.text = self.contractInfo.num;
    if ([self.contractInfo.num doubleValue] == 0) {
        ToastShowInWindow(@"合约数量为0吨");
    }
    self.categoryLbl.text = self.contractInfo.category_name;
    
    if ([self.contractInfo.depot_id isEqualToString:@"0"]) {
        //没有仓库，选择仓库
        self.storeChoseBtn.enabled = YES;
        self.storeNameLbl.text = @"请选择仓库";
    }else{
        //有仓库，获取仓库地址
        self.storeChoseBtn.enabled = YES;
        [self fetchStoreInfo];
    }
    
}
//获取仓库信息
- (void)fetchStoreInfo
{
    weak_Self(self);
    [[self.manager getStoreInfo:self.contractInfo.depot_id]subscribeNext:^(id x) {
        [weakSelf loadStoreInfo:x];
    } error:^(NSError *error) {
        ToastShowInWindow(@"无法获取仓库信息！");
    } completed:^{
        
    }];
}
- (void)loadStoreInfo:(DECXStoreObj *)store
{
    self.currentStore = store;
    self.storeNameLbl.text = store.depot_name.length==0?@"无":store.depot_name;
    self.storeManagerNameLbl.text = store.depotManager.name;
    self.storeManagerPhoneLbl.text = store.depotManager.mobile.length==0?@"无":store.depotManager.mobile;
    self.storeManagerTelLbl.text = store.depotManager.phone.length==0?@"无":store.depotManager.phone;
    self.storeManagerEmailLbl.text = store.depotManager.email.length==0?@"无":store.depotManager.email;
    self.storeAddressLbl.text = store.depot_addr;
}
- (IBAction)getStoreList:(id)sender
{
    weak_Self(self);
    [[self.manager getStoreList]subscribeNext:^(id x) {
        weakSelf.storeAry = x;
        [weakSelf layoutStoreListView];
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)layoutStoreListView
{
    if (!self.storePicker) {
        KSPickerView *picker = [[KSPickerView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        picker.delegate = self;
        [self.view.window addSubview:picker];
        self.storePicker = picker;
    }
    self.storePicker.dataAry = self.storeAry;
    [self.storePicker reloadData];
}
#pragma mark --- delegate
- (NSInteger)ksPickerView:(KSPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView == self.storePicker) {
        return self.storeAry.count;
    }
    return 0;
}
-(NSString*)ksPickerView:(KSPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView == self.storePicker) {
        DECXStoreObj *obj = self.storeAry[row];
        return obj.depot_name;
    }
    return @"";
}
- (void)ksPickViewDidConfirmSelected:(KSPickerView *)pickerView
{
    if (pickerView == self.storePicker) {
        NSInteger row = [self.storePicker selectedRowInComponent:0];
        DECXStoreObj *obj = self.storePicker.dataAry[row];
        [self loadStoreInfo:obj];
        [self.storePicker removeFromSuperview];
        self.storePicker = nil;
    }
}
- (void)ksPickerViewCancel:(KSPickerView *)pickerView
{
    if (pickerView == self.storePicker) {
        [self.storePicker removeFromSuperview];
        self.storePicker = nil;
    }
}

- (IBAction)uploadProductPicClick:(id)sender
{
    [self resignKeyBoard];
    weak_Self(self);
    DECXUploadPictureViewController *vc = StoryBoardViewController(@"Main", @"DECXUploadPictureViewController");
    vc.uploadBlock = ^(DECXPictureFile *file){
        if (file) {
            NSLog(@"file == %@",file);
            weakSelf.productLogoFile = file;
            weakSelf.productLogoMarkLbl.text = @"已上传";
        }
    };
    vc.uploadType = UploadPictureControllerTypeProductLogo;
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)uploadOtherPicClick:(id)sender
{
    [self resignKeyBoard];
    weak_Self(self);
    DECXUploadPictureViewController *vc = StoryBoardViewController(@"Main", @"DECXUploadPictureViewController");
    vc.uploadType = UploadPictureControllerTypeProductOwner;
    vc.uploadBlock = ^(DECXPictureFile *file){
        if (file) {
            NSLog(@"file == %@",file);
            weakSelf.productOwnerFile = file;
            weakSelf.productOwnerPicMarkLbl.text = @"已上传";
        }
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)resignKeyBoard
{
    [self.contractTxf resignFirstResponder];
    [self.billNoTxf resignFirstResponder];
    [self.markTxf resignFirstResponder];
    [self.stackTxf resignFirstResponder];
    [self.placeTxf resignFirstResponder];
    [self.qualityTxf resignFirstResponder];
    [self.productPriceTxf resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (void)gotoBack
{
    [DECXGlobal shareInstance].productLogo = nil;
    [DECXGlobal shareInstance].productProve = nil;
    
    [super gotoBack];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
